<template>
  <div class="record-request-detail">
    <header class="mb-8">
      <div class="flex items-center">
        <router-link to="/record/requests" class="mr-4 text-light-dark hover:text-primary">
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
          </svg>
        </router-link>
        <h1 class="glow-text">请求记录详情</h1>
      </div>
      <div class="tech-line mt-2"></div>
    </header>

    <div v-if="loading" class="flex justify-center items-center py-12">
      <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
    </div>

    <div v-else-if="!request" class="text-center py-12 text-light-dark">
      未找到请求记录或加载失败
    </div>

    <div v-else>
      <!-- 请求基本信息 -->
      <div class="card mb-8">
        <h2 class="text-xl font-medium mb-6">基本信息</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <div class="mb-4">
              <div class="text-light-dark mb-1">请求 ID</div>
              <div class="font-mono">{{ request._id }}</div>
            </div>
            <div class="mb-4">
              <div class="text-light-dark mb-1">服务名称</div>
              <div>{{ request.service_name }}</div>
            </div>
            <div class="mb-4">
              <div class="text-light-dark mb-1">请求方法</div>
              <span :class="{
                'badge badge-blue': request.method === 'GET',
                'badge badge-green': request.method === 'POST',
                'badge badge-purple': request.method === 'PUT',
                'badge badge-orange': request.method === 'DELETE',
                'badge badge-yellow': !['GET', 'POST', 'PUT', 'DELETE'].includes(request.method)
              }">{{ request.method }}</span>
            </div>
            <div class="mb-4">
              <div class="text-light-dark mb-1">请求路径</div>
              <div class="font-mono">{{ request.path }}</div>
            </div>
          </div>
          
          <div>
            <div class="mb-4">
              <div class="text-light-dark mb-1">状态码</div>
              <span :class="{
                'text-accent-blue': request.status_code < 300,
                'text-accent-yellow': request.status_code >= 300 && request.status_code < 400,
                'text-accent-orange': request.status_code >= 400 && request.status_code < 500,
                'text-accent-pink': request.status_code >= 500
              }">{{ request.status_code }}</span>
            </div>
            <div class="mb-4">
              <div class="text-light-dark mb-1">响应时间</div>
              <div>{{ request.response_time.toFixed(2) }} ms</div>
            </div>
            <div class="mb-4">
              <div class="text-light-dark mb-1">记录时间</div>
              <div>{{ formatTime(request.created_at) }}</div>
            </div>
            <div class="mb-4">
              <div class="text-light-dark mb-1">请求大小</div>
              <div>{{ formatBytes(request.request_size || 0) }}</div>
            </div>
            <div class="mb-4">
              <div class="text-light-dark mb-1">响应大小</div>
              <div>{{ formatBytes(request.response_size || 0) }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 请求详情 -->
      <div class="card mb-8">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-xl font-medium">请求详情</h2>
          <button @click="copyRequestCurl" class="btn btn-outline text-sm">
            <svg class="w-4 h-4 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"></path>
            </svg>
            复制为 cURL
          </button>
        </div>

        <div class="mb-6">
          <div class="text-light-dark mb-2">请求头</div>
          <div class="bg-dark-darker p-4 rounded-lg font-mono text-sm overflow-x-auto">
            <pre>{{ formatHeaders(request.request_headers) }}</pre>
          </div>
        </div>

        <div v-if="request.request_body">
          <div class="text-light-dark mb-2">请求体</div>
          <div class="bg-dark-darker p-4 rounded-lg font-mono text-sm overflow-x-auto">
            <pre>{{ formatBody(request.request_body, request.request_headers) }}</pre>
          </div>
        </div>
      </div>

      <!-- 响应详情 -->
      <div class="card mb-8">
        <h2 class="text-xl font-medium mb-6">响应详情</h2>

        <div class="mb-6">
          <div class="text-light-dark mb-2">响应头</div>
          <div class="bg-dark-darker p-4 rounded-lg font-mono text-sm overflow-x-auto">
            <pre>{{ formatHeaders(request.response_headers) }}</pre>
          </div>
        </div>

        <div v-if="request.response_body">
          <div class="text-light-dark mb-2">响应体</div>
          <div class="bg-dark-darker p-4 rounded-lg font-mono text-sm overflow-x-auto">
            <pre>{{ formatBody(request.response_body, request.response_headers) }}</pre>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="flex justify-between">
        <router-link to="/record/requests" class="btn btn-outline">
          返回列表
        </router-link>
        <div class="flex space-x-2">
          <button @click="convertToDefinition" class="btn btn-primary">
            <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7v8a2 2 0 002 2h6M8 7V5a2 2 0 012-2h4.586a1 1 0 01.707.293l4.414 4.414a1 1 0 01.293.707V15a2 2 0 01-2 2h-2M8 7H6a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2v-2"></path>
            </svg>
            转换为请求定义
          </button>
          <button @click="deleteRequest" class="btn btn-danger">
            <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
            </svg>
            删除请求
          </button>
        </div>
      </div>
    </div>

    <!-- 转换成功提示 -->
    <div v-if="showConvertSuccess" class="fixed inset-0 bg-dark-darker bg-opacity-75 flex items-center justify-center z-50">
      <div class="bg-dark-light rounded-lg w-full max-w-lg cyber-border">
        <div class="p-6">
          <div class="flex justify-between items-start mb-6">
            <h2 class="text-2xl font-bold">转换成功</h2>
            <button @click="showConvertSuccess = false" class="text-light-dark hover:text-primary">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>

          <div class="mb-6">
            <p>请求记录已成功转换为请求定义。</p>
          </div>

          <div class="flex justify-end">
            <button @click="showConvertSuccess = false" class="btn btn-outline mr-2">关闭</button>
            <router-link :to="`/request/definitions/${convertedDefinitionId}`" class="btn btn-primary">
              查看请求定义
            </router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { recordApi } from '../../api';

// 路由
const route = useRoute();
const router = useRouter();
const requestId = route.params.id as string;

// 状态变量
const loading = ref(false);
const request = ref<any>(null);
const showConvertSuccess = ref(false);
const convertedDefinitionId = ref('');

// 获取请求记录详情
const fetchRequestDetail = async () => {
  try {
    loading.value = true;
    const response = await recordApi.getRequestById(requestId);
    
    if (response && typeof response === 'object') {
      request.value = {
        ...response,
        response_time: response.response_time || 0,
        request_size: response.request_size || 0,
        response_size: response.response_size || 0
      };
    } else {
      // 模拟数据
      request.value = {
        _id: requestId,
        service_id: '1',
        service_name: 'user-service',
        path: '/api/users/123',
        method: 'GET',
        status_code: 200,
        response_time: 45.2,
        request_size: 1024,
        response_size: 2048,
        request_headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        },
        request_body: null,
        response_headers: {
          'Content-Type': 'application/json',
          'Cache-Control': 'no-cache',
          'X-Request-ID': '12345'
        },
        response_body: JSON.stringify({
          id: 123,
          name: 'John Doe',
          email: 'john@example.com',
          created_at: '2023-01-01T00:00:00Z'
        }),
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };
    }
  } catch (error) {
    console.error('获取请求记录详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 格式化请求头
const formatHeaders = (headers: any) => {
  if (!headers) return 'No headers';
  
  return Object.entries(headers)
    .map(([key, value]) => `${key}: ${value}`)
    .join('\n');
};

// 格式化请求/响应体
const formatBody = (body: any, headers: any) => {
  if (!body) return 'No body';
  
  // 检查内容类型
  const contentType = headers && headers['Content-Type'] ? headers['Content-Type'] : '';
  
  // 如果是 JSON
  if (contentType.includes('application/json')) {
    try {
      // 如果已经是字符串，尝试解析它
      if (typeof body === 'string') {
        const parsed = JSON.parse(body);
        return JSON.stringify(parsed, null, 2);
      }
      // 如果已经是对象，直接格式化
      return JSON.stringify(body, null, 2);
    } catch (e) {
      // 如果解析失败，返回原始内容
      return body;
    }
  }
  
  // 其他类型直接返回
  return body;
};

// 格式化字节大小
const formatBytes = (bytes: number) => {
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 格式化时间
const formatTime = (timestamp: string) => {
  if (!timestamp) return '未知';
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN');
};

// 复制为 cURL
const copyRequestCurl = () => {
  if (!request.value) return;
  
  let curl = `curl -X ${request.value.method} `;
  
  // 添加请求头
  if (request.value.request_headers) {
    Object.entries(request.value.request_headers).forEach(([key, value]) => {
      curl += `-H "${key}: ${value}" `;
    });
  }
  
  // 添加请求体
  if (request.value.request_body) {
    curl += `-d '${request.value.request_body}' `;
  }
  
  // 添加 URL
  const baseUrl = request.value.service_ip ? `http://${request.value.service_ip}:${request.value.service_port}` : '';
  curl += `"${baseUrl}${request.value.path}"`;
  
  // 复制到剪贴板
  navigator.clipboard.writeText(curl)
    .then(() => alert('已复制到剪贴板'))
    .catch(err => console.error('复制失败:', err));
};

// 转换为请求定义
const convertToDefinition = async () => {
  try {
    const response = await recordApi.convertToDefinition(requestId);
    
    if (response && response.definition_id) {
      convertedDefinitionId.value = response.definition_id;
      showConvertSuccess.value = true;
    } else {
      // 模拟成功
      convertedDefinitionId.value = '123456';
      showConvertSuccess.value = true;
    }
  } catch (error: any) {
    console.error('转换为请求定义失败:', error);
    alert(`转换为请求定义失败: ${error.response?.data?.error || error.message}`);
  }
};

// 删除请求记录
const deleteRequest = async () => {
  if (!confirm('确定要删除该请求记录吗？此操作不可恢复。')) return;

  try {
    await recordApi.deleteRequest(requestId);
    router.push('/record/requests');
  } catch (error: any) {
    console.error('删除请求记录失败:', error);
    alert(`删除请求记录失败: ${error.response?.data?.error || error.message}`);
  }
};

// 生命周期钩子
onMounted(() => {
  fetchRequestDetail();
});
</script>

<style scoped>
/* 可以添加组件特定的样式 */
</style>
